import React from 'react';
import { Button, Tab, Tag } from '@teamix/ui';
import jsonFormat from 'json-format';
import exceed from 'utils/apimap';
import ListEmpty from 'atComponents/ListEmpty';
import intl from '../../../../../../../../../../locale';

const prefix = 'webhook-history-dialog';

const TOO_LONG_TEXT = intl.get({
  id: 'code-assets.containers.historyModal.detail.TheResponseBodyIsToo',
  defaultMessage: 'Response Body过长，无法显示全部内容',
});
const failedReasonMap = {
  CONNECT_FAILED: intl.get({
    id: 'code-assets.containers.historyModal.detail.ConnectionFailed',
    defaultMessage: '连接失败',
  }),
  CONNECT_TIMEOUT: intl.get({
    id: 'code-assets.containers.historyModal.detail.ConnectionTimeout',
    defaultMessage: '连接超时',
  }),
  UNKNOWN_HOST: intl.get({
    id: 'code-assets.containers.historyModal.detail.UnknownDomainName',
    defaultMessage: '未知的域名',
  }),
  UNKNOWN_REASON: intl.get({
    id: 'code-assets.containers.historyModal.detail.UnknownError',
    defaultMessage: '未知错误',
  }),
};

export default class Detail extends React.Component {
  state = {
    activeTab: 'request',
    isRetrying: false,
  };

  onTabChange = (value) => {
    this.setState({
      activeTab: value,
    });
  };

  renderHeaders = (headers) => {
    let bodyDetail = null;
    if (headers) {
      const curHeaderEles = this.getStrEle(headers);
      bodyDetail = <pre className="light-well detail">{curHeaderEles}</pre>;
    }
    return (
      <div className="request">
        <div className="title">Headers</div>
        {bodyDetail}
      </div>
    );
  };

  getStrEle = (str) => {
    const arr = str.split('\n');
    const curStr = arr.map((item, index) => {
      if (index === arr.length - 1 && item && item.trim() === TOO_LONG_TEXT) {
        return <div className="body-too-long-tip">{item}</div>;
      }
      return <div>{item}</div>;
    });
    return curStr;
  };

  renderBody = (body) => {
    let bodyDetail = null;
    if (body) {
      let curBody;
      try {
        const bodyObj = JSON.parse(body);
        curBody = jsonFormat(bodyObj, {
          type: 'space',
          size: 2,
        });
      } catch (err) {
        console.error(err);
        curBody = body;
      }
      const curBodyEles = this.getStrEle(curBody);
      bodyDetail = <pre className="light-well detail">{curBodyEles}</pre>;
    }
    return (
      <div className="response">
        <div className="title">Body</div>
        {bodyDetail}
      </div>
    );
  };

  handleRetry = () => {
    const { pathResource } = window.FORCE;
    const { record, getList } = this.props;
    const { isRetrying } = this.state;
    if (isRetrying) {
      return;
    }
    this.setState({
      isRetrying: true,
    });

    exceed
      .fetch({
        api: 'project.webhook.history.retry',
        params: {
          projectId: pathResource.id,
          history_id: record.id,
        },
      })
      .then(() => {
        getList && getList(1);
      })
      .catch(() => {
        this.setState({ isRetrying: false });
      });
  };

  renderExtra = () => {
    const { record } = this.props;
    const { isRetrying } = this.state;
    if (record.responseStatus < 300 && record.responseStatus >= 200) {
      return null;
    }
    return (
      <Button type="primary" onClick={this.handleRetry} size="small" loading={isRetrying}>
        {intl.get({
          id: 'code-assets.containers.historyModal.detail.TryAgain',
          defaultMessage: '重试',
        })}
      </Button>
    );
  };

  render() {
    const { activeTab } = this.state;
    const { record } = this.props;

    return (
      <div className={`${prefix}-tab`}>
        <Tab
          onChange={this.onTabChange}
          activeKey={activeTab}
          extra={this.renderExtra()}
          animation={false}
        >
          <Tab.Item title={<span>Request</span>} key={'request'} />
          <Tab.Item
            title={
              <div className={`${prefix}-tab-title`}>
                <span>Response</span>
                {record.responseStatus ? (
                  <Tag
                    color={
                      record.responseStatus < 300 && record.responseStatus >= 200 ? 'green' : 'red'
                    }
                    style={{ margin: '0 4px' }}
                  >
                    {record.responseStatus}
                  </Tag>
                ) : (
                  <Tag style={{ margin: '0 4px' }}>
                    {intl.get({
                      id: 'code-assets.containers.historyModal.detail.NoResponse',
                      defaultMessage: '未响应',
                    })}
                  </Tag>
                )}
              </div>
            }
            key={'response'}
          />
        </Tab>
        {activeTab === 'request' ? (
          <div>
            {this.renderHeaders(record.requestHeaders)}
            {this.renderBody(record.requestData)}
          </div>
        ) : (
          <div>
            {record.responseStatus ? (
              <div>
                {this.renderHeaders(record.responseHeaders)}
                {this.renderBody(record.responseBody)}
              </div>
            ) : (
              <div className="empty-response">
                <ListEmpty
                  content={
                    record.failedReason
                      ? failedReasonMap[record.failedReason]
                      : intl.get({
                          id: 'code-assets.containers.historyModal.detail.NoResponseReceived',
                          defaultMessage: '未收到响应',
                        })
                  }
                  image="none"
                  className="table-list-empty"
                />
              </div>
            )}
          </div>
        )}
      </div>
    );
  }
}
